package com.s20y.generator.controller;

import com.s20y.generator.entity.Column;
import com.s20y.generator.entity.Table;
import com.s20y.generator.entity.TempletPathInfo;
import com.s20y.generator.mapper.IndexMapper;
import com.s20y.generator.utils.GeneratorUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

@Slf4j
@Controller
public class GeneratorController {
    @Autowired
    private IndexMapper indexMapper;

    @GetMapping
    public String index(ModelMap model){
        List<Table> tables = indexMapper.queryTables();
        model.addAttribute("tables", tables);
        GeneratorUtil.class.getPackageName();
        return "index";
    }

    @PostMapping("create")
    @ResponseBody
    public String create(Table table){
        Table tableInfo = indexMapper.getTable(table.getTableName());
        table.setTableName(tableInfo.getTableName());
        table.setComment(tableInfo.getComment());
        List<Column> cloumns = indexMapper.queryColumnsByTable(table.getTableName());
        table.setColumns(cloumns);
        GeneratorUtil.formatTable(table);
        List<String> generatorList = table.getGeneratorList();
        for(TempletPathInfo pathInfo : TempletPathInfo.values()) {
            if(generatorList.contains(pathInfo.getFileName())){
                GeneratorUtil.generatorCode(table, pathInfo);
            }
        }
        return "完成";
    }
}
